import os
import exifread
from PIL import Image

# 定义一个函数来遍历文件夹
def resize_images(directory, max_size_mb=4):
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.lower().endswith(('.png', '.jpg', '.jpeg')):  # 只处理图片文件
                file_path = os.path.join(root, file)
                file_size = os.path.getsize(file_path) / (1024 * 1024)  # 文件大小转换为MB
                if file_size > max_size_mb:
                    # 载入图片并保持EXIF信息
                    with Image.open(file_path) as img:
                        exif = img.info.get('exif')
                        # 调整图片大小
                        while file_size > max_size_mb:
                            img = img.resize((img.width // 2, img.height // 2), Image.LANCZOS)
                            img.save('pic/data/resized_' + file, 'JPEG', exif=exif)  # 保存到新文件
                            file_size = os.path.getsize('pic/data/resized_' + file) / (1024 * 1024)
                    print(f"Resized and saved: {file}")

# 调用函数，替换为你的目录
resize_images('pic')
